package com.itheima.web.client.userlogincontrol;


import com.itheima.web.Newuserregistration.UserAuthorityM;
import com.itheima.web.Newuserregistration.UserAuthorityMapper;
import com.itheima.web.Newuserregistration.UserMapper;
import com.itheima.web.client.userlogincontrol.Userregistration.User;
import com.itheima.web.client.userlogincontrol.Userregistration.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;


/**
 * @author 黄汉江
 * @date 2023/10/29 10:37
 * @description:
 */

@Controller
//@RestController
public class LoginController {
//    @Autowired
//    private IArticleService articleServiceImpl;
//    private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    // 向登录页面跳转，同时封装原始页面地址
    @GetMapping(value = "/login")
    public String login(HttpServletRequest request, Map map) {
        // 分别获取请求头和参数url中的原始访问路径
        String referer = request.getHeader("Referer");
        String url = request.getParameter("url");
        System.out.println("referer= " + referer);
        System.out.println("url= " + url);

        // 如果参数url中已经封装了原始页面路径，直接返回该路径
        if (url != null && !url.equals("")) {
            map.put("url", url);
            // 如果请求头本身包含登录，将重定向url设为空，让后台通过用户角色进行选择跳转
        } else if (referer != null && referer.contains("/login")) {
            map.put("url", "");
        } else {
            // 否则的话，就记住请求头中的原始访问路径
            map.put("url", referer);
        }
        return "comm/login";
    }

    // 对Security拦截的无权限访问异常处理路径映射
    @GetMapping(value = "/errorPage/{page}/{code}")
    public String AccessExecptionHandler(@PathVariable("page") String page, @PathVariable("code") String code) {
        return page + "/" + code;
    }

    //个人信息跳转
    @GetMapping("comm/geren")
    public String toLoginPage() {
        return "comm/geren";
    }


    @RequestMapping("/quit")//这里使用 @GetMapping会报错因为 @GetMapping是GET类型不是POST
    public String quit(){return "/comm/update_finish";}

    @RequestMapping("/updateError")//这里使用 @GetMapping会报错因为 @GetMapping是GET类型不是POST
    public String updateError(){return "/comm/update_error";}

@Autowired
private UserService userService;

    //用户修改提交处理
    @ResponseBody
    @PostMapping(value = "/updateUser")
    //通过RedirectView返回一个重定向的URL
    public RedirectView updateUser(@RequestParam String username, HttpServletRequest request){

        //获取应用上下文
        SecurityContext context = SecurityContextHolder.getContext();
        //获取用户相关信息
        Authentication authentication = context.getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();

        User user =new User();
        user = userService.findById(principal.getUsername());
        System.out.println(user);
        user.setUsername(username);
        System.out.println(user.getUsername());

        if (isUsernameExist(username) != null){
            return new RedirectView("/updateError", true);
        }else {
            userService.updateUser(user.getUsername(), user.getId());

            String csrf_token = request.getParameter("_update_finish");
            System.out.println(csrf_token);
            return new RedirectView("/quit", true);
        }


    }

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAuthorityMapper userAuthorityMapper;

    // 新用户注册
    @GetMapping("/toRegister") // http://localhost/toRegister
    public String showRegisterForm(Model model) {
        model.addAttribute("user", new User());
        return "client/registerUser";
    }

    // 用户注册提交处理
    @PostMapping(value = "/registerUser")
    public String registerUser(@RequestParam("username") String username,
                               @RequestParam("password") String password,
                               @RequestParam("email") String email) {
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(bCryptPasswordEncoder.encode(password)); // 对密码进行加密
        //user.setPassword(password);
        user.setEmail(email);
        if (isUsernameExist(username) != null) {
            return "comm/user_error";
        } else {
            userMapper.insertUser(user);
            // 获取新插入的用户ID
            Integer userId = userMapper.getNewUserId();
            // 插入用户权限关联信息到t_user_authority表
            UserAuthorityM userAuthorityM =new UserAuthorityM();
            userAuthorityM.setUserId(userId);
            userAuthorityM.setAuthorityId(2);
            userAuthorityMapper.insertUser(userAuthorityM);
            return "comm/user_finish";
        }
    }

    // 判断username是否存在
    public User isUsernameExist(String username) {
        User users = userMapper.findByUsername(username);
        return users;
    }



//    @GetMapping("/deleteUser")
//    public String deleteUser() {
//
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
//        int userId = userMapper.getNewUserId();
//        userMapper.deleteUser(userId);
//        userAuthorityMapper.deleteUserAuthority(userId);
//
//        Authentication authentication1 = SecurityContextHolder.getContext().getAuthentication();
//        if (authentication1 != null) {
//            SecurityContextHolder.getContext().setAuthentication(null);
//        }
//        return "comm/userdelete";
//    }

    // 用户注销页跳转
    @GetMapping("/deleteUser")
    public String deleteUser() {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 查询当前用户名id
        int userId = userMapper.getNewUserId();
        userMapper.deleteUser(userId);
        userAuthorityMapper.deleteUserAuthority(userId);
        // 清除用户
        Authentication authentication1 = SecurityContextHolder.getContext().getAuthentication();
        if (authentication1 != null) {
            SecurityContextHolder.getContext().setAuthentication(null);
        }
        return "comm/userdelete";
    }
}


